<?php
/**
  Interface of this moduel;

  $curUrl : string
  $itemsPerPage : int, numbers of items need to be showed per page.
  $itemsTotNum : int, numbers items return via query.
  $pageGetKeyname : string, the key name of $_GET[] relate to current page.
  $getarray : array, as " $_GET ".

  total varriable : 3
**/
function ouputgetkeyname($pageGetKeyname, $getarray){
  $getvarlist = '';
  foreach ($getarray as $key => $value) {
    if( !is_null($value) && $key != $pageGetKeyname){
      $appendstr = '&%s=%s';
      $getvarlist .= sprintf($appendstr, $key, $value);
    }else{
      continue;
    }
    return $getvarlist;
  }
}

function pagebar($curUrl, $itemsPerPage, $itemsTotNum, $pageGetKeyname, $getarray){
  if ( $itemsTotNum % $itemsPerPage == 0 ){
    $totPageNum =  (int)$itemsTotNum / $itemsPerPage;
  }else{
    $totPageNum =  ((int)($itemsTotNum / $itemsPerPage)) + 1;
  }
  $curpage = $getarray[$pageGetKeyname];
  $prepage = $curpage - 1;
  $nextpage = $curpage + 1;
  $urlformat =  '%s?%s=%d%s';
  $htmlstr = '<a href = "%s">%s</a>';

  $prevsurl = sprintf($urlformat, $curUrl, $pageGetKeyname, $prepage, ouputgetkeyname($pageGetKeyname, $getarray));
  $nexturl = sprintf($urlformat, $curUrl, $pageGetKeyname, $nextpage, ouputgetkeyname($pageGetKeyname, $getarray));

  if ($curpage == 1 || is_null($curpage)){
    $htmlouput = sprintf($htmlstr, '#', 'prev');
    echo $htmlouput;
  }else {
    $htmlouput = sprintf($htmlstr, $prevsurl, 'prev');
    echo $htmlouput;
  }

  for($pageindex =1 ; $pageindex <= $totPageNum; $pageindex++){
    $pageurl = sprintf($urlformat, $curUrl, $pageGetKeyname, $pageindex, ouputgetkeyname($pageGetKeyname, $getarray));
    $htmlouput = sprintf($htmlstr, $pageurl, $pageindex);
    echo $htmlouput;
  }

  if ($curpage == $totPageNum){
    $htmlouput = sprintf($htmlstr, "#", 'next');
    echo $htmlouput;
  }else {
    $htmlouput = sprintf($htmlstr, $nexturl, 'next');
    echo $htmlouput;
  }

}

?>
